import {
  _decorator,
  Component,
  EventKeyboard,
  Input,
  input,
  KeyCode,
  Node,
  RigidBody,
  Vec3,
} from "cc";
const { ccclass, property } = _decorator;

@ccclass("PlayMovement")
export class PlayMovement extends Component {
  @property(RigidBody) rigitbody: RigidBody;
  isLeftDown: boolean = false;
  isRightDown: boolean = false;
  @property forwardForce:number=0;
  @property sideForce:number=0;
  start() {
    input.on(Input.EventType.KEY_DOWN, this.onKeyDown, this);
    input.on(Input.EventType.KEY_UP, this.onKeyUp, this);
  }
  onDestroy () {
        input.off(Input.EventType.KEY_DOWN, this.onKeyDown, this);
        input.off(Input.EventType.KEY_UP, this.onKeyUp, this);
    }
  onKeyDown(event: EventKeyboard) {
    switch (event.keyCode) {
      case KeyCode.KEY_A:
        console.log("Press a key a");
        this.isLeftDown = true;
        break;
      case KeyCode.KEY_D:
        console.log("Press a key d");
        this.isRightDown = true;
        break;
    }
  }

  onKeyUp(event: EventKeyboard) {
    switch (event.keyCode) {
      case KeyCode.KEY_A:
        console.log("keyup a");
        this.isLeftDown = false;
        break;
      case KeyCode.KEY_D:
        console.log("keyup d");
        this.isRightDown = false;
        break;
    }
  }

  update(deltaTime: number) {
    let force = new Vec3(0, 0, this.forwardForce*deltaTime);
      this.rigitbody.applyForce(force);
      const sideForce=this.sideForce*deltaTime
    if (this.isLeftDown) {
      let force = new Vec3(sideForce, 0, 0);
      this.rigitbody.applyForce(force);
    }
    if (this.isRightDown) {
      let force = new Vec3(-sideForce, 0, 0);
      this.rigitbody.applyForce(force);
    }
    //判断失败
    if(this.node.position.y<=-10){
      this.enabled=false;
       let movemonent = this.node.getComponent(PlayMovement);
      movemonent.enabled = false;
      console.log("you lose")
    }
  }
}
